package second.servlet;


import second.dao.UserDao;
import second.dao.impl.UserDaoImpl;
import second.domain.User;
import second.utils.ActiveCodeUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


@WebServlet(name = "RegisterServlet", value = "/register")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1解决编码问题
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //2接受数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String repassword = request.getParameter("repassword");
        String email = request.getParameter("email");
        String gender = request.getParameter("gender");
        //3验证
        PrintWriter out = response.getWriter();
        if (username == null || username.trim().length() == 0) {
            out.write("用户名不能为空");
            return;
        }
        if (password == null || password.trim().length() == 0) {
            out.write("密码不能为空");
            return;
        }
        if (!password.equals(repassword)) {
            out.write("两次密码不一致");
            return;
        }
        if (email == null || email.trim().length() == 0) {
            out.write("邮箱不能为空");
            return;
        }
        if (gender == null || gender.trim().length() == 0) {
            out.write("性别不能为空");
            return;
        }

        //访问数据库
        User user = new User(null, username, password, email, gender, 0, 1, ActiveCodeUtils.createActiveCode());
        UserDao userDao = new UserDaoImpl();
        try {
            userDao.add(user);
            out.write("<h2>恭喜你，注册成功!3秒后，跳转到登录页面</h2>");
        } catch (Exception e) {
            e.printStackTrace();
            out.write("<h2>注册失败:" + e.getMessage() + "</h2>");
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
